package data

import (
	_ "database/sql"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type InsuranceRepo struct {
	o orm.Ormer
}

type InsuranceDto struct {
	Id        int     `orm:"pk;auto;column(id)"`
	MemberId  int     `orm:"column(member_id)"`
	WaybillId int     `orm:"column(waybill_id)"`
	Amount    float32 `orm:"column(amount)"`
	TypeId    int     `orm:"column(type_id)"`
	AgentId   int     `orm:"agent_id"`
	State     int     `orm:"column(state)"`
	ReqData   string  `orm:"column(req_data)"`
	ResData   string  `orm:"column(res_data)"`
}

func init() {
	orm.RegisterModel(new(InsuranceDto))
}

func (dto *InsuranceDto) TableName() string {
	return "t_insurance"
}

func (repo *InsuranceRepo) BeginTx() (err error) {
	repo.o = orm.NewOrm()
	if err = repo.o.Begin(); err != nil {
		repo.o.Rollback()
	}
	return
}

func (repo *InsuranceRepo) EndTx(ok bool) (err error) {
	if ok {
		err = repo.o.Commit()
	} else {
		err = repo.o.Rollback()
	}
	return
}

func (repo *InsuranceRepo) NewInsurance(dto InsuranceDto) error {
	_, err := repo.o.Insert(&dto)
	return err
}

func (repo InsuranceRepo) GetNotCompleteInsurance(waybillId int) (list []InsuranceDto, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("t_insurance").Filter("WaybillId", waybillId).Filter("State", 0).All(&list)
	return
}

func (repo InsuranceRepo) GetCompleteInsurance(waybillId int) (list []InsuranceDto, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("t_insurance").Filter("WaybillId", waybillId).Filter("State", 1).All(&list)
	return
}

func (repo InsuranceRepo) GetContractTime(waybillId int) (time string, err error) {
	var list orm.ParamsList
	o := orm.NewOrm()
	_, err = o.Raw(SQL_Order_Get_Contract_Time, waybillId).ValuesFlat(&list)
	if len(list) > 0 {
		time = list[0].(string)
	}
	return
}

func (repo InsuranceRepo) GetInsurancePayAmount(waybillId int) (list []InsuranceDto, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("t_insurance").Filter("WaybillId", waybillId).All(&list)
	return
}

func (repo InsuranceRepo) UpdateInsuranceCallback(dto InsuranceDto) error {
	o := orm.NewOrm()
	_, err := o.Update(&dto, "ResData", "ReqData", "State")
	return err
}

func (repo InsuranceRepo) CheckNotInsured(waybillId int) (ok bool, err error) {
	var cnt int64
	o := orm.NewOrm()
	if cnt, err = o.QueryTable("t_insurance").Filter("WaybillId", waybillId).Filter("State__in", []int{0, 1}).Count(); err == nil {
		ok = cnt == 0
	}
	return
}

func (repo InsuranceRepo) Cancel(waybillId int) (err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("t_insurance").
		Filter("waybill_id", waybillId).
		Update(orm.Params{"State": 3})
	return
}
